<?php

namespace App\Http\Controllers;

use App\Exceptions\AuthException;
use App\Libs\Company\SheetTemplateHandler\Manager;
use App\Models\SheetTemplate;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class SheetTemplateController extends Controller
{
    public function list(Request $request)
    {
        $request->validate([
            'name' => 'nullable|string|max:50',
            'type' => 'nullable|in:1,2',
            'frequency' => 'nullable|in:monthly,once',
            'page' => 'nullable|integer|min:1',
            'per_page' => 'nullable|integer',
        ]);

        if (!Auth::user()->hasPermissionTo('report-template')) {
            throw new AuthException();
        }
        $query = SheetTemplate::select(['id', 'name', 'description', 'type']);
        if ($request->name) {
            $query->where('name', 'like', "%{$request->name}%");
        }
        if ($request->type) {
            $query->where('type', $request->type);
        }
        if ($request->frequency) {
            $query->whereExists(function ($q) use ($request) {
                $q->select(\DB::raw(1))
                    ->from('sheet_pivot')
                    ->whereRaw('report_template_id = sheet_templates.id')
                    ->where('frequency', $request->frequency);
            });
        }
        $res = $query->orderBy('id', 'desc')->paginate($request->per_page);
        // echo $query->toSql();
        // var_dump($query->getBindings());
        // die();
        return responder()->success($res);
    }

    public function show(Request $request)
    {
        $request->validate([
            'id' => 'required|integer|exists:sheet_templates,id,deleted_at,NULL',
        ]);

        if (!Auth::user()->hasPermissionTo('report-template')) {
            throw new AuthException();
        }
        $model = SheetTemplate::find($request->id);
        if ($model->type == SheetTemplate::TYPE_REPORT) {
            $model['univer_data'] = Manager::createReportHandler($model)->renderTemplate();
        } else if ($model->type == SheetTemplate::TYPE_AGGREGATE) {
            $model['univer_data'] = Manager::createAggregateHandler($model)->renderTemplate();
        }
        unset($model['data']);
        return responder()->success($model);
    }
}
